package com.castle.fortress.admin.contract.info.service.impl;

import cn.hutool.core.util.StrUtil;

import com.castle.fortress.admin.utils.Sequence;
import com.castle.fortress.common.utils.ConvertUtil;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.castle.fortress.admin.contract.info.entity.ContractEntity;
import com.castle.fortress.admin.contract.info.dto.ContractDto;
import com.castle.fortress.admin.contract.info.mapper.ContractMapper;
import com.castle.fortress.admin.contract.info.service.ContractService;
import com.castle.fortress.admin.contract.review.entity.ContractReviewEntity;
import com.castle.fortress.admin.contract.review.service.ContractReviewService;
import com.castle.fortress.admin.contract.enums.StanceEnum;
import com.castle.fortress.admin.contract.enums.IntensityEnum;
import com.castle.fortress.admin.contract.enums.ReviewStatusEnum;
import com.castle.fortress.admin.contract.enums.ReviewMethodEnum;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import java.util.List;
import java.util.Date;
import com.castle.fortress.admin.rule.listRule.service.RuleListRuleService;
import com.castle.fortress.admin.rule.listRule.entity.RuleListRuleEntity;
import lombok.extern.slf4j.Slf4j;

/**
 * 合同信息表 服务实现类
 *
 * @author
 * @since 2025-04-23
 */
@Slf4j
@Service
public class ContractServiceImpl extends ServiceImpl<ContractMapper, ContractEntity> implements ContractService {

    @Autowired
    private ContractReviewService contractReviewService;

    @Autowired
    private RuleListRuleService ruleListRuleService;

    /**
    * 获取查询条件
    * @param contractDto
    * @return
    */
    public QueryWrapper<ContractEntity> getWrapper(ContractDto contractDto){
        QueryWrapper<ContractEntity> wrapper= new QueryWrapper();
        if(contractDto != null){
            ContractEntity contractEntity = ConvertUtil.transformObj(contractDto,ContractEntity.class);
            wrapper.like(contractEntity.getContractId() != null,"contract_id",contractEntity.getContractId());
            wrapper.like(StrUtil.isNotEmpty(contractEntity.getFileName()),"file_name",contractEntity.getFileName());
            wrapper.like(StrUtil.isNotEmpty(contractEntity.getFileUrl()),"file_url",contractEntity.getFileUrl());
            wrapper.like(contractEntity.getFileSize() != null,"file_size",contractEntity.getFileSize());
            wrapper.like(StrUtil.isNotEmpty(contractEntity.getContractType()),"contract_type",contractEntity.getContractType());
            wrapper.like(contractEntity.getContractAmount() != null,"contract_amount",contractEntity.getContractAmount());
            wrapper.like(StrUtil.isNotEmpty(contractEntity.getContractTerm()),"contract_term",contractEntity.getContractTerm());
            wrapper.like(StrUtil.isNotEmpty(contractEntity.getContentSummary()),"content_summary",contractEntity.getContentSummary());
            wrapper.like(StrUtil.isNotEmpty(contractEntity.getPartyA()),"party_a",contractEntity.getPartyA());
            wrapper.like(StrUtil.isNotEmpty(contractEntity.getPartyB()),"party_b",contractEntity.getPartyB());
            wrapper.like(contractEntity.getCreateTime() != null,"create_time",contractEntity.getCreateTime());
            wrapper.like(contractEntity.getUpdateTime() != null,"update_time",contractEntity.getUpdateTime());
            wrapper.like(contractEntity.getCreateUser() != null,"create_user",contractEntity.getCreateUser());
            wrapper.like(contractEntity.getUpdateUser() != null,"update_user",contractEntity.getUpdateUser());
			wrapper.eq(contractEntity.getIsDeleted() != null,"is_delete",contractEntity.getIsDeleted());
            wrapper.orderByDesc("create_time");
        }
        return wrapper;
    }


    @Override
    public IPage<ContractDto> pageContract(Page<ContractDto> page, ContractDto contractDto) {
        QueryWrapper<ContractEntity> wrapper = getWrapper(contractDto);
        Page<ContractEntity> pageEntity = new Page(page.getCurrent(), page.getSize());
        Page<ContractEntity> contractPage=baseMapper.selectPage(pageEntity,wrapper);
        Page<ContractDto> pageDto = new Page(contractPage.getCurrent(), contractPage.getSize(),contractPage.getTotal());
        pageDto.setRecords(ConvertUtil.transformObjList(contractPage.getRecords(),ContractDto.class));
        return pageDto;
    }

    /**
     * 使用自定义SQL分页查询合同信息
     * 
     * @param page 分页参数
     * @param contractDto 查询条件
     * @return 分页结果
     */
    @Override
    public IPage<ContractDto> pageContractWithSql(Page<ContractDto> page, ContractDto contractDto) {
        // 直接调用Mapper层的自定义SQL方法
        return baseMapper.pageContractWithSql(page, contractDto);
    }

    @Override
    public List<ContractDto> listContract(ContractDto contractDto){
        QueryWrapper<ContractEntity> wrapper = getWrapper(contractDto);
        List<ContractEntity> list = baseMapper.selectList(wrapper);
        return ConvertUtil.transformObjList(list,ContractDto.class);
    }

    /**
     * 获取合同和审核记录的详情
     * 根据合同ID，获取合同信息及其关联的审核记录
     *
     * @param contractId 合同ID
     * @return 包含合同信息和审核记录的DTO对象
     */
    @Override
    public ContractDto getContractAndReviewDetail(Long contractId) {
        if (contractId == null) {
            return null;
        }

        // 获取合同基本信息
        ContractEntity contractEntity = getById(contractId);
        if (contractEntity == null) {
            return null;
        }

        // 转换为DTO
        ContractDto contractDto = ConvertUtil.transformObj(contractEntity, ContractDto.class);

        // 获取关联的审核记录
        ContractReviewEntity reviewEntity = contractReviewService.getByContractId(contractId);
        if (reviewEntity != null) {
            // 填充审核信息
            contractDto.setStance(reviewEntity.getStance());
            contractDto.setIntensity(reviewEntity.getIntensity());
            contractDto.setRuleListId(reviewEntity.getRuleListId());
            contractDto.setReviewMethod(reviewEntity.getReviewMethod());

            // 此处可以添加更多审核相关信息
            // 示例：如果将来需要添加其他审核信息字段，可以在此处添加
            // contractDto.setNewField(reviewEntity.getSomeField());
        }

        // 返回包含合同和审核信息的DTO
        return contractDto;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long saveContractAndReview(ContractDto contractDto, String stance, String intensity, String ruleListId, String reviewMethod) {
        // 转换合同信息
        ContractEntity contractEntity = ConvertUtil.transformObj(contractDto, ContractEntity.class);
        Long contractId = contractEntity.getContractId();
        boolean isUpdate = contractId != null && contractId > 0;

        // 更新操作
        if (isUpdate) {
            // 检查合同是否存在
            ContractEntity existingContract = getById(contractId);
            if (existingContract == null) {
                return null; // 合同不存在，返回null
            }

            // 设置更新时间
            contractEntity.setUpdateTime(new Date());

            // 不要更改创建时间和创建人
            contractEntity.setCreateTime(existingContract.getCreateTime());
            contractEntity.setCreateUser(existingContract.getCreateUser());

            // 保持删除标记不变
            contractEntity.setIsDeleted(existingContract.getIsDeleted());

            // 更新合同实体
            boolean contractUpdated = updateById(contractEntity);
            if (!contractUpdated) {
                return null;
            }

            // 查找对应的审核记录
            ContractReviewEntity existingReview = contractReviewService.getByContractId(contractId);

            // 如果找到了审核记录，则更新
            if (existingReview != null) {
                existingReview.setStance(stance);
                existingReview.setIntensity(intensity);
                existingReview.setRuleListId(ruleListId);
                existingReview.setReviewMethod(reviewMethod);
                existingReview.setUpdateTime(new Date());

                // 如果有更新人信息，设置更新人
                if (contractEntity.getUpdateUser() != null) {
                    existingReview.setUpdateUser(contractEntity.getUpdateUser());
                }

                // 更新审核记录
                boolean reviewUpdated = contractReviewService.updateById(existingReview);
                return reviewUpdated ? contractId : null;
            }
            // 不存在审核记录，创建新的
            else {
                // 创建并保存合同审核记录
                ContractReviewEntity reviewEntity = new ContractReviewEntity();
                reviewEntity.setReviewId(Sequence.getInstance().nextId());
                reviewEntity.setContractId(contractId);
                reviewEntity.setStance(stance);
                reviewEntity.setIntensity(intensity);
                reviewEntity.setRuleListId(ruleListId);
                reviewEntity.setReviewMethod(reviewMethod);
                reviewEntity.setReviewStatus(ReviewStatusEnum.PENDING.getCode());
                reviewEntity.setCreateTime(new Date());

                // 如果有创建人信息，传递给审核记录
                if (contractEntity.getCreateUser() != null) {
                    reviewEntity.setCreateUser(contractEntity.getCreateUser());
                }

                // 保存审核记录
                boolean reviewSaved = contractReviewService.save(reviewEntity);
                return reviewSaved ? contractId : null;
            }
        }
        // 新增操作
        else {
            // 生成新的ID
            contractId = Sequence.getInstance().nextId();
            contractEntity.setContractId(contractId);

            // 设置创建时间
            if(contractEntity.getCreateTime() == null) {
                contractEntity.setCreateTime(new Date());
            }

            // 设置删除标志
            contractEntity.setIsDeleted(2);

            // 保存合同实体
            boolean contractSaved = this.save(contractEntity);
            if(!contractSaved) {
                return null;
            }

            // 创建并保存合同审核记录
            ContractReviewEntity reviewEntity = new ContractReviewEntity();
            reviewEntity.setReviewId(Sequence.getInstance().nextId());
            reviewEntity.setContractId(contractId);
            reviewEntity.setStance(stance);
            reviewEntity.setIntensity(intensity);
            reviewEntity.setRuleListId(ruleListId);
            reviewEntity.setReviewMethod(reviewMethod);
            reviewEntity.setReviewStatus(ReviewStatusEnum.PENDING.getCode());
            reviewEntity.setCreateTime(new Date());

            // 如果有创建人信息，传递给审核记录
            if(contractEntity.getCreateUser() != null) {
                reviewEntity.setCreateUser(contractEntity.getCreateUser());
            }

            // 保存审核记录
            boolean reviewSaved = contractReviewService.save(reviewEntity);

            return reviewSaved ? contractId : null;
        }
    }

    /**
     * 级联删除合同数据
     * 删除合同表数据的同时，级联删除与之关联的审核记录和规则关联数据
     *
     * @param contractId 合同ID
     * @return 是否删除成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cascadeDeleteContract(Long contractId) {
        if (contractId == null) {
            return false;
        }

        boolean success = true;

        try {
            // 1. 删除关联的审核记录
            QueryWrapper<ContractReviewEntity> reviewWrapper = new QueryWrapper<>();
            reviewWrapper.eq("contract_id", contractId);
            contractReviewService.remove(reviewWrapper);

            // 2. 删除关联的规则清单规则关联
            QueryWrapper<RuleListRuleEntity> ruleListRuleWrapper = new QueryWrapper<>();
            ruleListRuleWrapper.eq("contract_id", contractId);
            ruleListRuleService.remove(ruleListRuleWrapper);

            // 3. 删除合同主表数据
            this.removeById(contractId);

            return success;
        } catch (Exception e) {
            // 打印异常日志
            log.error("级联删除合同数据失败，合同ID：" + contractId, e);
            throw e; // 抛出异常，触发事务回滚
        }
    }
}

